package com.zzyl.nursing.service.impl;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.AIModelInvoker;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.vo.HealthReportVo;
import org.apache.xmlbeans.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 * 
 * @author gyf
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AIModelInvoker aiModelInvoker;

//    @Autowired
//    private ResourceLoader resourceLoader;

    @Value("classpath:prompts/prompt.txt")
    private Resource promptResource;
    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     * 
     * @param healthAssessmentDto 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto healthAssessmentDto)
    {
        //根据身份证号读取体检报告
        String context = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT, healthAssessmentDto.getIdCard());

        //提取完就删除缓存
        redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT, healthAssessmentDto.getIdCard());
        //调用千帆大模型,分析评估体检报告
        String prompt = getPrompt(context);
        String s = aiModelInvoker.qianfanInvoker(prompt);
        //将评估结果保存到数据库中

        //获取AI返回结果
        HealthReportVo parse = JSON.parseObject(s, HealthReportVo.class);
        //创建插入的健康评估对象
        HealthAssessment healthAssessment = new HealthAssessment();

        //注入老人姓名
        healthAssessment.setElderName(healthAssessmentDto.getElderName());
        //注入身份证号
        String idCard = healthAssessmentDto.getIdCard();
        healthAssessment.setIdCard(idCard);
        //生日 年龄 性别
        healthAssessment.setBirthDate(IDCardUtils.getBirthDateByIdCard(idCard));
        healthAssessment.setAge(IDCardUtils.getAgeByIdCard(idCard));
        healthAssessment.setGender(IDCardUtils.getGenderFromIdCard(idCard));
        //健康评分  和 风险等级
        healthAssessment.setHealthScore(String.valueOf(parse.getHealthAssessment().getHealthIndex()));
        healthAssessment.setRiskLevel(parse.getHealthAssessment().getRiskLevel());
        //是否建议入住
        double healthIndex = parse.getHealthAssessment().getHealthIndex();
        healthAssessment.setSuggestionForAdmission( healthIndex >= 60 ? 0 : 1);
        //推荐护理等级
        healthAssessment.setNursingLevelName(getNursingLevelName(healthIndex));
        //入住情况默认设置未入住
        healthAssessment.setAdmissionStatus(1);
        //总检日期
        healthAssessment.setTotalCheckDate(parse.getTotalCheckDate());
        //总检机构
        healthAssessment.setPhysicalExamInstitution(healthAssessmentDto.getPhysicalExamInstitution());
        //总检报告URL
        healthAssessment.setPhysicalReportUrl(healthAssessmentDto.getPhysicalReportUrl());
        //评估时间
        healthAssessment.setAssessmentTime(LocalDateTime.now());
        //报告总结
        healthAssessment.setReportSummary(parse.getSummarize());
        //疾病风险
        healthAssessment.setDiseaseRisk(JSON.toJSONString(parse.getRiskDistribution()));
        //异常分析
        healthAssessment.setAbnormalAnalysis(JSON.toJSONString(parse.getAbnormalData()));
        //健康系统分值
        healthAssessment.setSystemScore(JSON.toJSONString(parse.getSystemScore()));
        healthAssessmentMapper.insert(healthAssessment);

        return healthAssessment.getId();
    }

    /**
     * 获取护理等级
     * @param healthIndex
     * @return
     */
    private String getNursingLevelName(double healthIndex) {
        if (healthIndex > 100 || healthIndex < 0){
            throw new BaseException("健康指数范围错误");
        }

        if (healthIndex >= 90){
            return "四级护理等级";
        }else if (healthIndex >= 80){
            return "三级护理等级";
        }else if (healthIndex >= 70){
            return "二级护理等级";
        }else if (healthIndex >= 60){
            return "一级护理等级";
        }else{
            return "特技护理等级";
        }
    }

    /**
     * 获取prompt
     * @param context
     * @return
     */
    private String getPrompt(String context) {

        try {
            //从文件中读取模板
//            InputStream resourceAsStream = resourceLoader.getResourceAsStream("classpath:prompts/prompt.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(promptResource.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s= br.readLine()) != null){

                sb.append(s);
                if (s.contains("体检内容如下：")){
                    sb.append(context);
                }
            }

            return sb.toString();
        } catch (IOException e) {
            throw new BaseException("获取提示词失败");
        }
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.deleteById(id);
    }
}
